package asia.doing.common.config;

import asia.doing.common.Constants;
import asia.doing.common.enums.ResultCodeEnum;
import asia.doing.common.enums.RoleEnum;
import asia.doing.common.exception.CustomException;
import asia.doing.common.utils.TokenUtils;
import asia.doing.entity.Account;
import asia.doing.mapper.AdminMapper;
import asia.doing.mapper.UserMapper;
import cn.hutool.core.util.ObjectUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt拦截器
 */
@Component
public class AdminInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(AdminInterceptor.class);

    @Resource
    private AdminMapper adminMapper;

    @Resource
    private UserMapper userMapper;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Account account = TokenUtils.getCurrentUser();
        try {
            //如果是管理员
            if (RoleEnum.ADMIN.name().equals(account.getRole())) {
                return true;
            }else if(ObjectUtil.isNull(account)){
                throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
            }
            else{
                return false;
            }
        } catch (Exception e) {
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
    }
}